﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DTcms.Model;
using DTcms.BLL;
using Newtonsoft.Json;
using DTcms.Common;
using DTcms.API.Payment.wxpay;
using System.Text;

namespace Demon.WebApi.Controllers
{
    [RoutePrefix("api/wxapi")]
    public class WX_LoginController : ApiController
    { /// <summary>
      /// 微信小程序 获取openid 
      /// </summary>
      /// 
      /// <returns></returns>
        [HttpGet, Route("wxlogin")]
        public Models.wxResult wxlogin(string code)
        {
            Models.wxResult res = new Models.wxResult();
            try
            {
                DTcms.BLL.weixin_account accbll = new DTcms.BLL.weixin_account();
                DTcms.Model.weixin_account acc = accbll.GetModel(1);
                if (acc == null) {
                    res.code = "1";
                    res.message = "获取appid 失败，请先配置appid！";
                }
                string url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
                url = url.Replace("APPID", acc.appid);
                url = url.Replace("SECRET", acc.appsecret);
                url = url.Replace("JSCODE", code);
                var returndata = Helper.Utils.HttpGet(url);
                //DAL.FileHelper.WriteTextLog("GetUserInfo", "报文：" + returndata, DateTime.Now);
                // 成功 "{"session_key":"TFkl48Udw8lB6KwPGbgbCQ==","openid":"o7zOm5A8OlhqKjtZHuXBJKVeMmmM"}"
                // 失败 "{"errcode":40029,"errmsg":"invalid code, hints: [ req_id: vkNebawgE-y720Oa ]"}"
                if (returndata.IndexOf("errcode") > 0)
                {
                    res.code = "E";
                    res.message = returndata;
                    return res;
                }
                Models.wx_openresult result = JsonConvert.DeserializeObject<Models.wx_openresult>(returndata);

                
                DTcms.BLL.users_wx wxbll = new DTcms.BLL.users_wx();

                var rr=wxbll.WXLogin(result.openid);
                if (rr.IndexOf("E:") >= 0)
                {
                    Guid token = new Guid();
                    DTcms.Model.users_wx wxmo = new DTcms.Model.users_wx();
                    wxmo.OpenId = result.openid;
                    wxmo.Token = token;
                    wxmo.AddTime = DateTime.Now;
                    wxbll.Add(wxmo);
                    result.token = token.ToString();

                }
                else {
                    var rrs = rr.Split(';');
                    result.token = rrs[0];
                    if (rrs.Length == 3) {
                        result.username = rrs[1];
                        result.user_pwd = rrs[2];
                    }
                }

                res.code = "S";
                //res.message = returndata;
                res.message = JsonConvert.SerializeObject(result);
                return res;

            }
            catch (Exception ex)
            {
                res.code = "E";
                res.message =JsonConvert.SerializeObject(ex) ;
                return res;

            }

        }
        /// <summary>
        /// 小程序注册
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("wxRegister")]
        public Models.wxResult wxRegister(string token,string NickName,string gender,string city, string province,string country,string avatarUrl) {
            Models.wxResult res = new Models.wxResult();
            try {

                DTcms.Model.users uu = new DTcms.Model.users();

                return res;
            }
            catch (Exception ex) {
                res.code = "E";
                res.message = ex.Message;
                return res;
            }
        }

        /// <summary>
        /// 用户升级订单
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("UserOrderPay")]
        public Models.wxResult UserOrderPay(string user_name, string user_pwd, int group_id,string txtParentMobile)
        {
            Models.wxResult res = new Models.wxResult();
            try
            {
                if (string.IsNullOrEmpty(user_name) || string.IsNullOrEmpty(user_pwd))
                {
                    res.code = "E";
                    res.message = "您的登录信息有误，请退出系统后重新登录！";
                  
                    return res;
                }
                DTcms.Model.users userModel = new DTcms.BLL.users().GetModel(user_name, user_pwd, 0, 1, true);
                if (userModel == null)
                {
                    res.code = "E";
                    res.message = "您的登录信息有误，请退出系统后重新登录！";
                    return res;
                  
                   
                }


                int _group_id = group_id;
                string _parent_mobile = txtParentMobile;
                if (_group_id == 0)
                {
                    res.code = "E";
                    res.message = "错误提示：未指定升级ID！";
                    return res;
                }

                //Demon 20200229 取消IOS端认证会员的支付，直接返回支付失败！
                if (_group_id == 2)// && _systemType != "android" && !string.IsNullOrWhiteSpace(_systemType)
                {
                    res.code = "E";
                    res.message = "认证会员已取消，目前平台只支持vip会员！";
                    return res;
                   
                }
                string _body = string.Empty;
                decimal _amount = 0M;
                //switch (_group_id)
                //{
                //    case 2:
                //        _body = "开通298元VIP会员";
                //        _amount = 298;
                //        break;
                //    case 3:
                //        _body = "开通2880元钻石会员";
                //        _amount = 2880;
                //        break;
                //}
                #region///Demon 修改 获取会员价格的方式 从会员级别表中获取
                ///Demon 修改 获取会员价格的方式 从会员级别表中获取
                DTcms.BLL.user_groups ugbll = new DTcms.BLL.user_groups();
                DTcms.Model.user_groups ugmodel = ugbll.GetModelByGrage(_group_id);
                _body = "开通" + ugmodel.price + ugmodel.title;
                _amount = ugmodel.price;
                #endregion


                string _order_no = "M" + Utils.GetOrderNumber();

                DTcms.BLL.member_order bll = new DTcms.BLL.member_order();
                DTcms.Model.member_order model = new DTcms.Model.member_order();

                model.order_no = _order_no;
                model.user_id = userModel.id;
                model.group_id = _group_id;
                model.amount = _amount;
                model.add_time = DateTime.Now;
                model.payment_id = 1;
                model.remark = _body;
                model.parent_mobile = _parent_mobile;

                int result = bll.Add(model);
                if (result == 0)
                {
                    res.code = "E";
                    res.message = "错误提示：保存订单时出错！";
                    return res;
                  
                }

                /// ##流程https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_4&index=3
                ///1、小程序内调用登录接口，获取到用户的openid,api参见公共api【小程序登录API】
                ///2、商户server调用支付统一下单，api参见公共api【统一下单API】
                ///3、商户server调用再次签名，api参见公共api【再次签名】
                ///4、商户server接收支付通知，api参见公共api【支付结果通知API】
                ///5、商户server查询支付结果，api参见公共api【查询订单API】
                //第一步先生成一个签名
                string sendUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                WxPayData data = new WxPayData();
                data.SetValue("appid", "wxf3b482c702bdb291"); //公众账号ID
                data.SetValue("mch_id", "1504256031"); //商户号
                data.SetValue("device_info", "web"); //自定义参数，可以为终端设备号(门店号或收银设备ID)，PC网页或公众号内支付可以传"WEB"
                data.SetValue("nonce_str", Helper.Utils.GenerateNonceStr()); //随机字符串
                data.SetValue("sign", data.MakeSign("SrdyeR5v23cClIsgI0Dvs5UwCCOTXSa7")); //签名
                data.SetValue("sign_type","MD5"); //签名
                data.SetValue("body", _body); //商品描述
                data.SetValue("out_trade_no", _order_no); //商户订单号
                //data.SetValue("total_fee", (Convert.ToDouble(_amount) * 100).ToString()); //订单总金额,以分为单位
                data.SetValue("total_fee", "1"); //订单总金额,以分为单位
                data.SetValue("spbill_create_ip", DTRequest.GetIP()); //终端IP
                data.SetValue("trade_type", "JSAPI");//交易类型
                data.SetValue("notify_url", "https://www.shicaiquanzi.com/payment/notify_url.aspx"); //异步通知url
               
               
               
                
                string xml = data.ToXml(); //转换成XML
                string response = HttpService.Post(xml, sendUrl, false, 6); //发送请求
                Utils.WriteTextLog("UserOrderPay", response, DateTime.Now);
                WxPayData wd = new WxPayData();
                wd.FromXml(response);
                if (wd.GetValue("return_code").ToString() == "SUCCESS")
                {
                    //开始组织微信需要的结构
                    WxPayData newdata = new WxPayData();
                    newdata.SetValue("appid", wd.GetValue("appid").ToString());
                    newdata.SetValue("partnerid", "1504256031");
                    newdata.SetValue("prepayid", wd.GetValue("prepay_id").ToString());
                    newdata.SetValue("package", "Sign=WXPay");
                    newdata.SetValue("noncestr",Helper.Utils.GenerateNonceStr());
                    newdata.SetValue("timestamp", Helper.Utils.GenerateTimeStamp());
                    newdata.SetValue("sign", newdata.MakeSign("SrdyeR5v23cClIsgI0Dvs5UwCCOTXSa7"));

                    string json_str = newdata.ToJson();
                    StringBuilder strTxt = new StringBuilder();
                    strTxt.Append("{");
                    strTxt.Append("\"status\":1");
                    strTxt.Append(",\"payData\":" + json_str);
                    strTxt.Append("}");

                    res.code = "S";
                    res.message = strTxt.ToString();
                    return res;
                    
                }
                else
                {
                    res.code = "E";
                    res.message = "支付过程中遇至未知错误，请重试！";
                    return res;
                }


                return res;
            }
            catch (Exception ex)
            {
                res.code = "E";
                res.message = ex.Message;
                return res;
            }
        }

    }
}
